package com.milk.service.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.dubbo.annotation.DubboService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.milk.model.entity.admin.Admin;
import com.milk.model.entity.admin.Function;
import com.milk.model.entity.admin.Role;
import com.milk.service.admin.dao.AdminDao;
import com.milk.service.admin.dao.FunctionDao;
import com.milk.service.admin.dao.RoleDao;

@Service
@DubboService(interfaceClass = AdminService.class)
public class AdminServiceImpl implements AdminService{
	
	
	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private AdminDao adminDao;
	@Autowired
	private FunctionDao functionDao;
	@Autowired
	private RoleDao roleDao;

	@Transactional
	public long save(Admin admin) {
		
		adminDao.save(admin);
		
		return admin.getId();
	}

	@Transactional
	public void update(Admin admin) {
		int result = adminDao.update(admin);
	}

	@Transactional
	public void delete(long adminId) {
		int result = adminDao.delete(adminId);
	}

	public Admin findById(long adminId) {
		Map<String,Object> params = new HashMap<String,Object>(1);
		params.put("id", adminId);
		return adminDao.findByMap(params);
	}

	public Admin findByUserName(String username) {
		Map<String,Object> params = new HashMap<String,Object>(1);
		params.put("username", username);
		return adminDao.findByMap(params);
	}

	public List<Admin> query(Map<String, Object> params) {
		return adminDao.query(params);
	}

	@Transactional
	public void upToAdministrator(long adminId) {
		Admin admin = findById(adminId);
		admin.setAdministrator(true);
		adminDao.update(admin);
	}

	@Transactional
	public void downFromAdministrator(long adminId) {
		Admin admin = findById(adminId);
		admin.setAdministrator(false);
		adminDao.update(admin);
	}

	@Transactional
	public void addFunctionToRole(List<Map<String,Object>> functions) {
		functionDao.roleFunctionSave(functions);
	}

	@Transactional
	public long saveRole(Role role) {
		roleDao.save(role);
		return role.getId();
	}

	@Transactional
	public long deleteRole(long roleId) {
		return roleDao.delete(roleId);
	}

	public List<Role> queryRoles(Map<String, Object> params) {
		return roleDao.query(params);
	}

	@Transactional
	public long saveFunction(Function function) {
		functionDao.save(function);
		return function.getId();
	}

	@Transactional
	public long deleteFunction(long funcId) {
		return functionDao.delete(funcId);
	}

	public List<Function> queryAllFunction(Map<String, Object> params) {
		return functionDao.query(params);
	}
	
}
